package com.zmh.wt.healthmonitor.service.impl;

import com.github.benmanes.caffeine.cache.Cache;
import com.zmh.wt.healthmonitor.constant.CacheConstant;
import com.zmh.wt.healthmonitor.constant.Constants;
import com.zmh.wt.healthmonitor.mapper.Handler.MapResultHander;
import com.zmh.wt.healthmonitor.mapper.WindturbineMapper;
import com.zmh.wt.healthmonitor.service.WindturbineService;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author MH.Zhang
 * @Classname WindturbineServiceImpl
 * @Date 2023/2/23 21:17
 */
@Service
public class WindturbineServiceImpl implements WindturbineService {

    private final static String WF_STATUS = "wf_status";

    @Resource
    WindturbineMapper windturbineMapper;

    @Qualifier("commonCache")
    @Autowired
    Cache<String, Object> caffeineCache;

    @Qualifier("stateCache")
    @Autowired
    Cache<String, Object> stateCache;

    /**
     * 查询单个风机的状态
     *
     * @param windfarm
     * @param windturbine
     * @return
     */
    @Override
    public Integer queryWindturbineStatus(String windfarm, Integer windturbine) {
        return null;
    }

    /**
     * 查询数据库所有风机状态(正常-故障)
     *
     * @param windfarm
     * @return
     */
    @Override
    public Map<String, Integer> queryDbAllStatus(String windfarm) {
        MapResultHander mapResultHander = new MapResultHander("windturbine", "status");
        windturbineMapper.queryAllWindturbineStatus(windfarm, mapResultHander);
        Map mapResults = mapResultHander.getMapResults();
        return mapResults;
    }

    /**
     * 查询所有风机状态(正常-故障-未连接)
     *
     * @param windfarm
     * @return
     */
    @Override
    public Map<String, Integer> queryAllStatContainsUnconnected(String windfarm) {
        if (windfarm == null || windfarm.length() == 0) {
            return new HashMap<>(0);
        }

        //生成key
        String wfStatusKey = CacheConstant.getKey(CacheConstant.KEY_WIND_TURBINE, WF_STATUS, windfarm);
        caffeineCache.getIfPresent(wfStatusKey);
        Map<String, Integer> wfStatus = (Map<String, Integer>) caffeineCache.asMap().get(wfStatusKey);

        //无记录则构造缓存
        if (wfStatus == null || wfStatus.isEmpty()) {
            //构造未连接状态Map
            wfStatus = constructStatusMap(windfarm);
        }

        //状态过滤
        Set<String> wtIds = wfStatus.keySet();
        List<String> wtStatusKeys = wtIds.stream().map(cur -> CacheConstant.getWtStatusKey(windfarm, cur)).collect(Collectors.toList());
        Map<@NonNull String, @NonNull Object> allPresent = stateCache.getAllPresent(wtStatusKeys);

        Map<String, Integer> finalWfStatus = wfStatus.entrySet().stream().
                peek(entry -> entry.setValue((Integer) allPresent.getOrDefault(CacheConstant.getWtStatusKey(windfarm,entry.getKey()), Constants.UNCONNECTED))).
                collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        //更新缓存
        caffeineCache.put(wfStatusKey, finalWfStatus);

        return finalWfStatus;
    }

    private String getWtIdFromCacheKey(String key) {
        int idx = key.length() - 1;
        StringBuilder sb = new StringBuilder();
        while (key.charAt(idx) != '_'){
            sb.append(key.charAt(idx));
            idx--;
        }
        return sb.reverse().toString();
    }

    /**
     * 更新风机状态缓存
     *
     * @param windfarm
     * @param windturbine
     * @param status
     * @return
     */
    @Deprecated
    @Override
    public Integer updateWindturbineCacheStatus(String windfarm, Integer windturbine, Integer status) {

        //生成key
        String wtStatusKey = CacheConstant.getKey(CacheConstant.KEY_WIND_TURBINE, WF_STATUS, windfarm);
        stateCache.getIfPresent(wtStatusKey);
        Map<String, Integer> wtStatus = (Map<String, Integer>) stateCache.asMap().get(wtStatusKey);

        //无记录则构造缓存
        if (wtStatus == null || wtStatus.isEmpty()) {
            //构造未连接状态Map
            wtStatus = constructStatusMap(windfarm);
            //更新缓存
            stateCache.put(wtStatusKey, wtStatus);
        }

        //更新状态
        wtStatus.put(windturbine.toString(), status);
        stateCache.put(wtStatusKey, wtStatus);

        return Constants.SUCCESS_INT;
    }

    /**
     * 构建初始化风机叶片状态Map
     *
     * @param windfarm
     * @return
     */
    private Map<String, Integer> constructStatusMap(String windfarm) {

        //查数据库
        Map<String, Integer> wtStatusDB = queryDbAllStatus(windfarm);

        //将所有风机连接状态置为未连接
        Map<String, Integer> wtStatus = wtStatusDB.entrySet().stream().
                peek(entry -> entry.setValue(Constants.UNCONNECTED)).
                collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        return wtStatus;
    }
}
